/*
 * Copyright (C) 2015 The Sven Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.core.os;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.core.util.LogUtil;

/**
 * Created by Tan on 14-3-20.
 * email hellotanm@gmail.com
 */
@SuppressWarnings("unused")
public class PackMan {

    public static ArrayList<AppInfo> getAllApp(Context context) {

        ArrayList<AppInfo> appList = new ArrayList<>();

        if (context.getPackageManager() == null)
            return null;

        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);

        for (PackageInfo packageInfo : packages) {

            AppInfo tmpInfo = new AppInfo();
            tmpInfo.appName = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
            tmpInfo.packageName = packageInfo.packageName;
            tmpInfo.versionName = packageInfo.versionName;
            tmpInfo.versionCode = packageInfo.versionCode;
            tmpInfo.appIcon = packageInfo.applicationInfo.loadIcon(context.getPackageManager());

            appList.add(tmpInfo);
        }
        return appList;
    }

    public static boolean verifyMount(Context context, String packageName) {

        if (context.getPackageManager() == null)
            return false;

        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);

        for (PackageInfo packageInfo : packages) {

            if (packageName.equals(packageInfo.packageName)) {
                return true;
            }

        }

        return false;
    }

    public static void installApp(Context context, String fileName) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)), "application/vnd.android.package-archive");
        context.startActivity(intent);

    }

    public static void toAppByPackage(Context context, String appPackage) {

        if (context == null || appPackage == null)
            return;

        if (context.getPackageManager() == null)
            return;

        Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackage);

        if (intent == null)
            return;

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);

    }

    public static String getTopActivityClassName(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> rti = manager.getRunningTasks(Integer.MAX_VALUE);

        return rti.get(0).topActivity.getClassName();
    }

    public static Map<String, String> getVersion(String pack, Context context) {

        if (context.getPackageManager() == null)
            return null;

        PackageInfo packInfo;
        Map<String, String> result = new HashMap<>();

        if ("this".equals(pack)) {
            pack = context.getPackageName();
        }

        try {
            packInfo = context.getPackageManager().getPackageInfo(pack, 0);

            if (packInfo.versionName != null)
                result.put("versionName", packInfo.versionName);

            result.put("versionCode", String.valueOf(packInfo.versionCode));
            return result;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("deprecation")
    public static String getCurrentApp(Context context) {

        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> rti = manager.getRunningTasks(Integer.MAX_VALUE);

        return rti.get(0).topActivity.getPackageName();
    }

    @SuppressWarnings("deprecation")
    public static boolean activityIsTop(Context context, String name) {

        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> rtis = manager.getRunningTasks(Integer.MAX_VALUE);

        if (!rtis.isEmpty()) {

            RunningTaskInfo rti = rtis.get(0);
            LogUtil.e(rti.topActivity.getClassName());
            LogUtil.e(rti.baseActivity.getClassName());

            return rti.topActivity.getClassName().equals(name) ||
                    rti.baseActivity.getClassName().equals(name) ||
                    rti.topActivity.getPackageName().equals(name) ||
                    rti.baseActivity.getPackageName().equals(name) ||
                    name.contains(rti.topActivity.getPackageName());
        }
        return false;
    }

    @SuppressWarnings("deprecation")
    public static boolean isRunning(Context context, String packageName) {

        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> rtis = manager.getRunningTasks(Integer.MAX_VALUE);

        for (RunningTaskInfo rti : rtis) {
            LogUtil.e(rti.topActivity.getPackageName());
            LogUtil.e(rti.baseActivity.getPackageName());
            if (rti.topActivity.getPackageName().equals(packageName) ||
                    rti.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }

        return false;
    }

    public static boolean isServiceRunning(Context context, String serviceComponentName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = manager.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
            ComponentName service = serviceInfo.service;
            String className = service.getClassName();
            if (className.equals(serviceComponentName)) {
                return true;
            }
        }

        return false;
    }


    public static boolean ExistSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static class AppInfo {

        public String appName = "";

        public String packageName = "";

        public String versionName = "";

        public int versionCode = 0;

        public Drawable appIcon = null;

        public AppInfo() {

        }

        public AppInfo(String appName) {
            this.appName = appName;
        }

        public AppInfo(String appName, String packageName) {
            this.appName = appName;
            this.packageName = packageName;
        }

        public AppInfo(String appName, String packageName, String versionName) {
            this.appName = appName;
            this.packageName = packageName;
            this.versionName = versionName;
        }

        public AppInfo(String appName, String packageName, String versionName, int versionCode) {
            this.appName = appName;
            this.packageName = packageName;
            this.versionName = versionName;
            this.versionCode = versionCode;
        }

        public String getAppName() {
            return appName;
        }

        public void setAppName(String appName) {
            this.appName = appName;
        }

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        public String getVersionName() {
            return versionName;
        }

        public void setVersionName(String versionName) {
            this.versionName = versionName;
        }

        public int getVersionCode() {
            return versionCode;
        }

        public void setVersionCode(int versionCode) {
            this.versionCode = versionCode;
        }

        public Drawable getAppIcon() {
            return appIcon;
        }

        public void setAppIcon(Drawable appIcon) {
            this.appIcon = appIcon;
        }
    }
}
